package com.ivanceras.server;

import java.util.ArrayList;
import java.util.List;

import javax.jdo.PersistenceManager;
import javax.jdo.Query;

import com.ivanceras.client.SimulationService;
import com.ivanceras.model.Choice;
import com.ivanceras.model.Question;
import com.ivanceras.model.Questionnaire;
import com.google.gwt.user.server.rpc.RemoteServiceServlet;


/**
 * The server side implementation of the RPC service.
 */

@SuppressWarnings("serial")
public class SimulationServiceImpl extends RemoteServiceServlet implements
		SimulationService {
	/**
	 * retrieve all the questions from the specified questionnaire ID
	 */
	public Questionnaire getQuestions(long questionnaireID){
		PersistenceManager pm = PMF.get().getPersistenceManager();
	    Query query = pm.newQuery(Question.class, "questionnaireID == "+questionnaireID);
	    System.out.println("query:"+query.toString());
		Questionnaire qnr = pm.getObjectById(Questionnaire.class,questionnaireID);
		try{
			List<Question> results = (List<Question>)query.execute();
	        if (results.iterator().hasNext()) {
	            for (Question qn : results) {
	            	qn.questionnaireID = questionnaireID;
	        	    Query chQuery = pm.newQuery(Choice.class, "questionID == "+qn.questionID);
	        	    List<Choice> choices = (List<Choice>)chQuery.execute();
	        	    for(Choice ch:choices){
	        	    	qn.choiceList.add(ch);
	        	    }
	                qnr.addQuestion(qn);
	            }
	        } else {
	            System.out.println("No questionnaires.. create a new one!");
	        }
		}finally{
			pm.close();
		}
		 return qnr;
	}
	/**
	 * Retrieve all questionnaire (info only) from the datastore
	 */
	public ArrayList<Questionnaire> getQuestionnaires(){
		PersistenceManager pm = PMF.get().getPersistenceManager();
		System.out.println("Getting questionnaires....");
		ArrayList<Questionnaire> qnrList = new ArrayList<Questionnaire>();
		 
		Query query = pm.newQuery(Questionnaire.class);
		try{
			List<Questionnaire> results = (List<Questionnaire>)query.execute();
	        if (results.iterator().hasNext()) {
	            for (Questionnaire pQnr : results) {
	                qnrList.add(pQnr);
	            }
	        } else {
	            System.out.println("No questionnaires.. create a new one!");
	        }
		}finally{
			pm.close();
		}
		 return qnrList;
	}
	/**
	 * used when a questionnaire info is edited
	 */
	public Questionnaire saveQuestionnaire(Questionnaire oqnr){
		PersistenceManager pm = PMF.get().getPersistenceManager();
		Questionnaire pqnr;
		if(null == oqnr.questionnaireID){
			pqnr = new Questionnaire(oqnr.title, oqnr.description);
		}else{//retreive the old one then modify
		    pqnr = pm.getObjectById(Questionnaire.class, oqnr.questionnaireID);
		}
	    pqnr.title = oqnr.title; 
    	pqnr.description = oqnr.description;
    	pqnr.items = oqnr.items;
    	pqnr.choices = oqnr.choices;

    	pm.makePersistent(pqnr);
	    pm.close();
		return pqnr;
	}
	@Override
	public Question saveQuestion(Question qn) {
		PersistenceManager pm = PMF.get().getPersistenceManager();
		Question pqn; //persistent question
		if(null == qn.questionID){
			if(null == qn.questionnaireID){
				System.out.println("Error: Question should belong to a questionnaire");
				return null;
			}
			pqn = new Question();//Question ID is generated here...
		}else{
			pqn = pm.getObjectById(Question.class,qn.questionID);
		}
		//continue the execution and then save
		System.out.println("p questionnaireID: "+pqn.questionnaireID);
		//pqn.setQuestionnaireID(qn.questionnaireID.intValue());
		pqn.questionnaireID = qn.questionnaireID;
		System.out.println("p questionnaireID: "+pqn.questionnaireID);
		pqn.setText(qn.text);
		if(null == qn.questionID){
			pm.makePersistent(pqn);
		}
		for(Choice ch:qn.choiceList){
			Choice pch;
			if(null == ch.choiceID){
				pch = new Choice();
				pch.questionID = pqn.questionID;
			}else{
				pch = pm.getObjectById(Choice.class,ch.choiceID);
			}
			pch.isCorrect = ch.isCorrect;
			pch.text = ch.text;
			if(null == ch.choiceID){
				pm.makePersistent(pch);
			}
			pqn.addChoice(pch);//important to note here, need to persist the object first before adding to other object or else will not save other fields
		}
		pm.close();
		updateQuestionnaireMetaData(qn.questionnaireID);
		return pqn;
	}
	/**
	 * update questionnaire meta data when a new question is saved
	 * @param questionnaireID
	 */
	public void updateQuestionnaireMetaData(Long questionnaireID){
		//getQuestions(questionnaireID);
	}

}
